﻿using AutoMapper;
using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class UpdateroleCommandHander : IRequestHandler<UpdateroleCommand, ApiResult<object>>
    {
        public readonly IRepistory<Role> repistory;
        public readonly IMapper mapper;
        public UpdateroleCommandHander(IRepistory<Role> repistory, IMapper mapper)
        {
            this.repistory = repistory;
            this.mapper = mapper;
        }
        public Task<ApiResult<object>> Handle(UpdateroleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> apiResult= new ApiResult<object>();
            var result = repistory.GetAll().Where(x => x.RoleName == request.RoleName);
            if (result.Count() > 0) 
            {
                apiResult.code = Renum.修改失败;
                apiResult.Message = "角色名称已存在重复".ToString();
                return Task.FromResult(apiResult);

            }
         
                var result1 = mapper.Map<Role>(request);
                repistory.Update(result1);
                result1.Updatedate=DateTime.Now;
                result1.Updateor = "杀马特";
                var result2 = repistory.Update(result1);
                apiResult.code=Renum.修改成功;
                apiResult.Message=Renum.修改成功.ToString();
                apiResult.Data = result2;
                return Task.FromResult(apiResult);

            
        }
    }
}
